<template>
  <div class="system-user">
    <div class="table-container">
      <table-header
        v-model:columns="columns"
        table-id="systemUser"
        :buttons="['refresh', 'add', 'quickSearch', 'colSetting']"
        role-prefix="system:user"
        @refresh="getUserList"
        @create="handleCreate"
        @change="handleInputChange"
      />
      <table-base
        :columns="columns"
        :table-data="userList"
        :total="total"
        :page-index="searchParams.pageIndex"
        :page-size="searchParams.pageSize"
        :loading="loading"
        @page-change="handlePageChange"
      >
        <template #avatar="scope">
          <img
            style="width: 40px; height: 40px; border-radius: 50%"
            :src="scope.row.avatar || '/default_avatar.png'"
            alt="avatar"
          />
        </template>
        <template #sex="scope">
          <span>{{ scope.row.sex === 1 ? "男" : "女" }}</span>
        </template>
        <template #state="scope">
          <el-tag v-if="scope.row.state === 1" type="success">正常</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
        <template #create-time="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
        <template #option="scope">
          <el-button
            v-btn-permission="'system:user:edit'"
            type="primary"
            text
            class="btn-text btn-text-primary"
            @click="handleEdit(scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-btn-permission="'system:user:delete'"
            type="danger"
            text
            class="btn-text btn-text-danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </table-base>
    </div>
    <modal-delete ref="modalDeleteRef" @confirm="handleConfirmDelete" />
    <modal-form
      ref="modalFormRef"
      :title="modalTitle"
      :modal-config="modalConfigGetter"
      :form-data="formData"
      @submit="handleSubmit"
    >
      <template #avatar>
        <picture-upload :picture-list="pictureList" @on-success="onUploadSuccess" />
      </template>
    </modal-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from "vue"
import { getUserById, getUserByPage, userCreate, userDelete, userEdit } from "@/api/user"
import { showErrorToast, showSuccessToast } from "@/utils/toast"
import { columns } from "./config/content.config"
import { modalConfig } from "./config/modal.config"
import TableHeader from "@/components/base/TableHeader.vue"
import TableBase from "@/components/base/TableBase.vue"
import ModalDelete from "@/components/base/ModalDelete.vue"
import ModalForm from "@/components/base/ModalForm.vue"
import { FORM_MODE } from "@/constants"
import { formatDateTime } from "@/utils/format"

interface UserFormData {
  id?: number
  userName: string
  passWord?: string
  nickName: string
  sex: number
  phone: string
  avatar: string
  roleIds: number[]
}

const modalDeleteRef = ref<InstanceType<typeof ModalDelete> | null>(null)
const modalFormRef = ref<InstanceType<typeof ModalForm> | null>(null)

const loading = ref(false)
const total = ref(0)
const userList = ref<UserResponse[]>([])
const pictureList = ref<string[]>([])

const formMode = ref<string>(FORM_MODE.CREATE)
const initialFormData = {
  userName: "",
  passWord: "",
  nickName: "",
  sex: 1,
  phone: "",
  avatar: "",
  roleIds: []
}
const formData = ref<UserFormData>({ ...initialFormData })

const modalTitle = computed(() => {
  return formMode.value === FORM_MODE.CREATE ? "新增用户" : "编辑用户"
})

const modalConfigGetter = computed(() => {
  if (formMode.value === FORM_MODE.CREATE) {
    return modalConfig
  } else {
    // 编辑不需要密码
    return {
      ...modalConfig,
      formItems: modalConfig.formItems.filter((item) => item.prop !== "passWord")
    }
  }
})

// 搜索参数
const searchParams = reactive<UserQueryRequest>({
  key: "",
  pageIndex: 1,
  pageSize: 10
})

const handlePageChange = (pageIndex: number, pageSize: number) => {
  searchParams.pageIndex = pageIndex
  searchParams.pageSize = pageSize
  getUserList()
}

const onUploadSuccess = (fileUrl: string) => {
  pictureList.value = [fileUrl]
  formData.value.avatar = fileUrl
}

const handleCreate = () => {
  pictureList.value = []
  formData.value = { ...initialFormData }
  formMode.value = FORM_MODE.CREATE
  modalFormRef.value?.openModal()
}

const handleEdit = async (id: number) => {
  if (!id) return

  formMode.value = FORM_MODE.EDIT
  try {
    const res = await getUserById({ id })
    if (res.data) {
      formData.value = {
        id: res.data.id,
        userName: res.data.userName,
        nickName: res.data.nickName,
        sex: res.data.sex,
        phone: res.data.phone,
        avatar: res.data.avatar,
        roleIds: []
      }
      pictureList.value = [res.data.avatar]
    }
    modalFormRef.value?.openModal()
  } catch (error: any) {
    showErrorToast(error.message)
  }
}

const handleSubmit = async (formInfo: UserFormData) => {
  try {
    if (formMode.value === FORM_MODE.CREATE) {
      const params: UserCreateRequest = {
        userName: formInfo.userName,
        passWord: formInfo.passWord!,
        nickName: formInfo.nickName,
        sex: formInfo.sex,
        phone: formInfo.phone,
        roleIds: []
      }
      const res = await userCreate(params)
      if (res.data) {
        getUserList()
        showSuccessToast("新增成功")
        modalFormRef.value?.closeModal()
      }
    } else {
      const params: UserEditRequest = {
        id: formInfo.id!,
        userName: formInfo.userName,
        nickName: formInfo.nickName,
        sex: formInfo.sex,
        phone: formInfo.phone,
        roleIds: []
      }
      const res = await userEdit(params)
      if (res.data) {
        getUserList()
        showSuccessToast("编辑成功")
        modalFormRef.value?.closeModal()
      }
    }
  } catch (error: any) {
    showErrorToast(error.message)
  }
}

const handleDelete = (id: number) => {
  if (!id) return
  modalDeleteRef.value?.openModal(id)
}

const handleConfirmDelete = async (ids: number[]) => {
  if (ids.length <= 0) return

  try {
    const res = await userDelete({
      id: ids[0]
    })
    if (res.data) {
      getUserList()
      showSuccessToast("删除成功")
      modalDeleteRef.value?.closeModal()
    }
  } catch (error: any) {
    showErrorToast(error.message)
  }
}

const doSearch = () => {
  searchParams.pageIndex = 1
  getUserList()
}

const handleInputChange = (value: string) => {
  searchParams.key = value
  doSearch()
}

onMounted(() => {
  getUserList()
})

async function getUserList() {
  loading.value = true
  try {
    const res = await getUserByPage(searchParams)
    if (res.data) {
      userList.value = res.data.list ?? []
      total.value = res.data.totalCount ?? 0
    }
  } catch (error: any) {
    showErrorToast(error.message)
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped></style>
